<template>
  <ResponsiveLayout 
    layout="default" 
    :show-sidebar="false" 
    :safe-area="true"
    content-padding="0"
  >
    <!-- 移动端导航 -->
    <MobileNavigation
      v-if="isMobile"
      :title="'小智医疗助手'"
      :show-bottom-nav="true"
      :bottom-nav-items="bottomNavItems"
      :active-bottom-key="activeBottomKey"
      @bottom-nav-click="handleBottomNavClick"
    >
      <template #nav-right>
        <el-button type="text" @click="handleNotifications" size="small">
          <el-icon><Bell /></el-icon>
        </el-button>
      </template>
    </MobileNavigation>

    <!-- 桌面端头部 -->
    <template #header>
      <header v-if="!isMobile" class="dashboard-header">
        <div class="header-content">
          <div class="logo-section">
            <OptimizedImage src="/OIP.webp" alt="小智医疗" class="logo" :lazy="false" :width="40" :height="40" />
            <h1>小智医疗版</h1>
          </div>
          
          <div class="user-section">
            <el-button type="text" @click="handleNotifications">
              <el-icon><Bell /></el-icon>
              通知
            </el-button>
            <el-dropdown @command="handleUserCommand">
              <div class="user-info">
                <OptimizedImage :src="userStore.userInfo?.avatar || '/OIP.webp'" alt="用户头像" class="user-avatar" :lazy="false" :width="32" :height="32" />
                <span class="username">{{ userStore.userInfo?.realName || userStore.userInfo?.username }}</span>
                <el-icon><ArrowDown /></el-icon>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">
                    <el-icon><User /></el-icon>
                    个人资料
                  </el-dropdown-item>
                  <el-dropdown-item command="settings">
                    <el-icon><Setting /></el-icon>
                    设置
                  </el-dropdown-item>
                  <el-dropdown-item divided command="logout">
                    <el-icon><SwitchButton /></el-icon>
                    退出登录
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </header>
    </template>

    <!-- 主要内容区域 -->
    <div class="dashboard-container" :class="{ 'mobile-layout': isMobile }">
      <!-- 加载状态 -->
      <div v-if="loading" class="dashboard-loading">
        <SkeletonLoader type="card" :rows="3" :show-actions="true" />
        <div class="skeleton-grid">
          <SkeletonLoader v-for="i in gridColumns" :key="i" type="card" :rows="2" />
        </div>
        <div class="skeleton-recent">
          <SkeletonLoader type="list" :count="3" />
          <SkeletonLoader type="list" :count="3" />
        </div>
      </div>
      
      <!-- 主要内容 -->
      <div v-else>
    
    <!-- 主要内容区域 -->
    <main class="dashboard-main">
      <!-- 欢迎区域 -->
      <section class="welcome-section">
        <div class="welcome-card">
          <div class="welcome-content">
            <h2>欢迎回来，{{ userStore.userInfo?.realName || '用户' }}！</h2>
            <p>今天是 {{ currentDate }}，祝您身体健康！</p>
          </div>
          <div class="welcome-stats">
            <div class="stat-item">
              <div class="stat-number">{{ appointments.length }}</div>
              <div class="stat-label">待就诊</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">{{ chatCount }}</div>
              <div class="stat-label">咨询次数</div>
            </div>
          </div>
        </div>
      </section>
      
      <!-- 功能卡片区域 -->
      <section class="features-section">
        <div class="features-grid">
          <!-- AI智能咨询 -->
          <div class="feature-card primary" @click="$router.push('/chat')">
            <div class="feature-icon">
              <el-icon size="40"><ChatDotRound /></el-icon>
            </div>
            <div class="feature-content">
              <h3>AI智能咨询</h3>
              <p>与小智医生对话，获取专业医疗建议</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 预约挂号 -->
          <div class="feature-card success" @click="$router.push('/appointment')">
            <div class="feature-icon">
              <el-icon size="40"><Calendar /></el-icon>
            </div>
            <div class="feature-content">
              <h3>预约挂号</h3>
              <p>在线预约医生，查看可用时间</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 症状自评 -->
          <div class="feature-card danger" @click="$router.push('/symptom')">
            <div class="feature-icon">
              <el-icon size="40"><DocumentChecked /></el-icon>
            </div>
            <div class="feature-content">
              <h3>症状自评</h3>
              <p>AI智能分析症状，提供专业建议</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 健康数据分析 -->
          <div class="feature-card info" @click="$router.push('/analytics')">
            <div class="feature-icon">
              <el-icon size="40"><DataAnalysis /></el-icon>
            </div>
            <div class="feature-content">
              <h3>健康分析</h3>
              <p>数据可视化分析，洞察健康趋势</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 通知中心 -->
          <div class="feature-card warning" @click="$router.push('/notifications')">
            <div class="feature-icon">
              <el-icon size="40"><Bell /></el-icon>
            </div>
            <div class="feature-content">
              <h3>通知中心</h3>
              <p>查看系统通知和健康提醒</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 健康档案 -->
          <div class="feature-card warning" @click="$router.push('/health')">
            <div class="feature-icon">
              <el-icon size="40"><Document /></el-icon>
            </div>
            <div class="feature-content">
              <h3>健康档案</h3>
              <p>管理个人健康信息和医疗记录</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- API测试 -->
          <div class="feature-card secondary" @click="$router.push('/api-test')">
            <div class="feature-icon">
              <el-icon size="40"><Setting /></el-icon>
            </div>
            <div class="feature-content">
              <h3>API测试</h3>
              <p>验证所有API接口的可访问性</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
          
          <!-- 个人中心 -->
          <div class="feature-card info" @click="$router.push('/profile')">
            <div class="feature-icon">
              <el-icon size="40"><User /></el-icon>
            </div>
            <div class="feature-content">
              <h3>个人中心</h3>
              <p>查看和编辑个人信息设置</p>
            </div>
            <div class="feature-arrow">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </div>
        </div>
      </section>
      
      <!-- 最近活动 -->
      <section class="recent-section">
        <div class="section-header">
          <h3>最近活动</h3>
          <el-link type="primary">查看全部</el-link>
        </div>
        
        <div class="recent-cards">
          <!-- 最近预约 -->
          <div class="recent-card">
            <div class="card-header">
              <el-icon><Calendar /></el-icon>
              <span>最近预约</span>
            </div>
            <div class="card-content">
              <div v-if="appointments.length > 0" class="appointment-list">
                <div v-for="appointment in appointments.slice(0, 3)" :key="appointment.id" class="appointment-item">
                  <div class="appointment-info">
                    <div class="doctor-name">{{ appointment.doctorName }}</div>
                    <div class="appointment-time">{{ appointment.date }} {{ appointment.time }}</div>
                  </div>
                  <div class="appointment-status" :class="appointment.status">
                    {{ getStatusText(appointment.status) }}
                  </div>
                </div>
              </div>
              <div v-else class="empty-state">
                <p>暂无预约记录</p>
                <el-button type="primary" size="small" @click="$router.push('/appointment')">
                  立即预约
                </el-button>
              </div>
            </div>
          </div>
          
          <!-- 健康提醒 -->
          <div class="recent-card">
            <div class="card-header">
              <el-icon><Bell /></el-icon>
              <span>健康提醒</span>
            </div>
            <div class="card-content">
              <div class="reminder-list">
                <div class="reminder-item">
                  <div class="reminder-icon">💊</div>
                  <div class="reminder-text">记得按时服药</div>
                </div>
                <div class="reminder-item">
                  <div class="reminder-icon">🏃</div>
                  <div class="reminder-text">今日运动目标：30分钟</div>
                </div>
                <div class="reminder-item">
                  <div class="reminder-icon">💧</div>
                  <div class="reminder-text">记得多喝水</div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
      </div>
    </div>
  </ResponsiveLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useLoadingStore } from '../stores/loading'
import { useResponsive } from '../utils/responsive'
import { ElMessage, ElMessageBox } from 'element-plus'
import ResponsiveLayout from '../components/ResponsiveLayout.vue'
import MobileNavigation from '../components/MobileNavigation.vue'
import OptimizedImage from '../components/OptimizedImage.vue'
import SkeletonLoader from '../components/SkeletonLoader.vue'
import {
  User,
  Setting,
  SwitchButton,
  ArrowDown,
  ArrowRight,
  MessageBox,
  Calendar,
  Document,
  DocumentChecked,
  DataAnalysis,
  Clock,
  Warning,
  Bell,
  House,
  ChatDotRound
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const loadingStore = useLoadingStore()
const { isMobile, isTablet } = useResponsive()

// 页面加载状态
const loading = ref(true)

// 响应式网格列数
const gridColumns = computed(() => {
  if (isMobile.value) return 1
  if (isTablet.value) return 2
  return 4
})

// 底部导航配置
const bottomNavItems = ref([
  { key: 'dashboard', label: '首页', icon: 'House' },
  { key: 'chat', label: 'AI咨询', icon: 'ChatDotRound' },
  { key: 'symptom', label: '症状自评', icon: 'DocumentChecked' },
  { key: 'appointment', label: '预约', icon: 'Calendar' },
  { key: 'notifications', label: '通知', icon: 'Bell' },
  { key: 'analytics', label: '数据分析', icon: 'DataAnalysis' },
  { key: 'api-test', label: 'API测试', icon: 'Setting' },
  { key: 'profile', label: '我的', icon: 'User' }
])

const activeBottomKey = ref('dashboard')

// 底部导航点击处理
const handleBottomNavClick = (key) => {
  activeBottomKey.value = key
  if (key !== 'dashboard') {
    router.push(`/${key}`)
  }
}

// 通知处理
const handleNotifications = () => {
  router.push('/notifications')
}

const chatCount = ref(12) // 模拟数据
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

const appointments = computed(() => userStore.appointments)

const getStatusText = (status) => {
  const statusMap = {
    confirmed: '已确认',
    pending: '待确认',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

const handleUserCommand = async (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'settings':
      // TODO: 实现设置页面
      ElMessage.info('设置功能开发中...')
      break
    case 'logout':
      try {
        await ElMessageBox.confirm(
          '确定要退出登录吗？',
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        userStore.logout()
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch {
        // 用户取消
      }
      break
  }
}

onMounted(async () => {
  try {
    // 显示页面加载状态
    loadingStore.showPageLoading('dashboard', {
      title: '加载仪表板数据...',
      tips: ['正在获取用户信息...', '加载预约数据...', '获取健康提醒...']
    })
    
    // 模拟数据加载过程
    await new Promise(resolve => setTimeout(resolve, 800))
    
    // 模拟加载用户数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 加载用户数据
    userStore.loadAppointments()
    
    await new Promise(resolve => setTimeout(resolve, 300))
    
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    ElMessage.error('加载数据失败，请刷新重试')
  } finally {
    // 隐藏加载状态
    loading.value = false
    loadingStore.hidePageLoading('dashboard')
  }
})
</script>

<style scoped>
.dashboard-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.mobile-layout {
  padding: 16px;
  padding-top: 70px; /* 为移动端导航栏留出空间 */
  padding-bottom: 80px; /* 为底部导航栏留出空间 */
}

.dashboard-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 70px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo {
  width: 45px;
  height: 45px;
  border-radius: 50%;
  object-fit: cover;
}

.logo-section h1 {
  color: #2c3e50;
  font-size: 24px;
  font-weight: 600;
  margin: 0;
}

.user-section {
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 8px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.user-avatar {
  width: 35px;
  height: 35px;
  border-radius: 50%;
  object-fit: cover;
}

.username {
  color: #2c3e50;
  font-weight: 500;
}

.dashboard-main {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.welcome-section {
  margin-bottom: 30px;
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 30px;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-content h2 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.welcome-content p {
  margin: 0;
  opacity: 0.9;
  font-size: 16px;
}

.welcome-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 4px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1));
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 12px;
  padding: 16px 20px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.stat-number::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.stat-number:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
  border-color: rgba(255, 255, 255, 0.5);
}

.stat-number:hover::before {
  left: 100%;
}

.stat-label {
  font-size: 14px;
  opacity: 0.8;
}

.features-section {
  margin-bottom: 30px;
}

.features-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.feature-card {
  background: white;
  border-radius: 16px;
  padding: 25px;
  display: flex;
  align-items: center;
  gap: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.feature-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.feature-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.feature-card.primary .feature-icon {
  background: linear-gradient(135deg, #409eff, #67c23a);
  color: white;
}

.feature-card.success .feature-icon {
  background: linear-gradient(135deg, #67c23a, #85ce61);
  color: white;
}

.feature-card.warning .feature-icon {
  background: linear-gradient(135deg, #e6a23c, #f7ba2a);
  color: white;
}

.feature-card.info .feature-icon {
  background: linear-gradient(135deg, #909399, #b1b3b8);
  color: white;
}

.feature-card.secondary .feature-icon {
  background: linear-gradient(135deg, #8e44ad, #9b59b6);
  color: white;
}

.feature-content {
  flex: 1;
}

.feature-content h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.feature-content p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
  line-height: 1.4;
}

.feature-arrow {
  color: #c0c4cc;
  transition: color 0.3s;
}

.feature-card:hover .feature-arrow {
  color: #409eff;
}

.recent-section {
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.recent-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 20px;
}

.recent-card {
  background: white;
  border-radius: 16px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  color: #2c3e50;
  font-weight: 600;
}

.appointment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.appointment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.doctor-name {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.appointment-time {
  font-size: 12px;
  color: #7f8c8d;
}

.appointment-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.appointment-status.confirmed {
  background: #f0f9ff;
  color: #409eff;
}

.appointment-status.pending {
  background: #fdf6ec;
  color: #e6a23c;
}

.empty-state {
  text-align: center;
  padding: 20px;
  color: #7f8c8d;
}

.reminder-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reminder-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.reminder-icon {
  font-size: 20px;
}

.reminder-text {
  color: #2c3e50;
  font-size: 14px;
}

/* 骨架屏样式 */
.dashboard-loading {
  padding: 20px;
}

.skeleton-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin: 20px 0;
}

.skeleton-recent {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-container {
    padding: 12px;
  }
  
  .mobile-layout {
    padding: 12px;
    padding-top: 60px;
    padding-bottom: 70px;
  }
  
  .dashboard-header {
    padding: 16px;
    margin-bottom: 20px;
  }
  
  .logo-section h1 {
    font-size: 20px;
  }
  
  .welcome-section {
    padding: 20px;
    margin-bottom: 20px;
  }
  
  .welcome-title {
    font-size: 24px;
  }
  
  .welcome-subtitle {
    font-size: 14px;
  }
  
  .features-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
    margin-bottom: 20px;
  }
  
  .feature-card {
    padding: 16px;
  }
  
  .feature-title {
    font-size: 16px;
  }
  
  .feature-description {
    font-size: 12px;
  }
  
  .recent-section {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .recent-card {
    padding: 16px;
  }
  
  .skeleton-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .skeleton-recent {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .dashboard-loading {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .mobile-layout {
    padding: 8px;
    padding-top: 55px;
    padding-bottom: 65px;
  }
  
  .features-grid {
    grid-template-columns: 1fr;
    gap: 12px;
  }
  
  .feature-card {
    padding: 12px;
  }
  
  .recent-card {
    padding: 12px;
  }
}

/* 平板适配 */
@media (min-width: 769px) and (max-width: 1024px) {
  .features-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 大屏幕优化 */
@media (min-width: 1200px) {
  .dashboard-container {
    max-width: 1200px;
    margin: 0 auto;
  }
}

@media (max-width: 768px) {
  .dashboard-main {
    padding: 20px 15px;
  }
  
  .welcome-card {
    flex-direction: column;
    text-align: center;
    gap: 20px;
  }
  
  .welcome-stats {
    gap: 20px;
  }
  
  .features-grid {
    grid-template-columns: 1fr;
  }
  
  .recent-cards {
    grid-template-columns: 1fr;
  }
  
  .header-content {
    padding: 0 10px;
  }
  
  .logo-section h1 {
    font-size: 20px;
  }
}
</style>